//
//  CPTabBar.swift
//  WeiBo1
//
//  Created by chengpeng on 16/3/4.
//  Copyright © 2016年 chengpeng. All rights reserved.
//

import UIKit

class CPTabBar: UITabBar {
    
    //撰写按钮点击的闭包回调
    var composeButtonClickClosure: (()->())?

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //添加子控件
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置视图
    private func setupUI(){
        
        addSubview(composeButton)
    
    }
    
    override func layoutSubviews() {
        //
        super.layoutSubviews()
        
        //调整其他按钮的位置和宽度
        let itemW =  self.frame.width / 5
        
        var index = 0
        
        //1.取到对应按钮
        for value in self.subviews {
            
            //如果是UIBarButton
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!){
                
                
                //2.计算出其他按钮的位置大小
                //2.1计算X和 width
                let x = CGFloat(index) * itemW
                
                //3.设置
                value.frame.size.width = itemW
                value.frame.origin.x = x
                
                index++
                
                //如果发现下一次遍历的第3个按钮，那么就往后一个位置
                if index == 2 {
                    index++
                }
            }
        }
  
        //调整加号按钮的位置
        composeButton.center = CGPoint(x:self.center.x, y :self.frame.height * 0.5)
    }
    
    func composeButtonClick (){
        
        //因为当前是一个View 不具有弹出控制器的功能，所以需要将事件抛出给控制器
        print("撰写按钮")
        
        //执行回调的闭包
        composeButtonClickClosure?()
    }
    
    //懒加载控件 
    
    private lazy var composeButton: UIButton = {
    
        let button = UIButton()
        
        
        //给按钮添加点击事件
        button.addTarget(self, action: "composeButtonClick", forControlEvents: .TouchUpInside)
        
        //设置不同状态下的背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        
        //设置不同状态下的图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        
        
        
        
        //设置按钮大小
        button.sizeToFit()
        
        return button
        
    }()

}
